package bots

import (
	"errmsg"
	"errors"
	"fmt"
	"github.com/astaxie/beego/logs"
	"smart_home/api/utils"
	"time"
	"tools"
)

var (
	tokenKey = "bot:%s:%s"
)

// @title 设置bot token
// @param key string true token key
// @param value string true token
// @param platform string true 平台
func SetToken(key string, value interface{}, platform string, timeout ...time.Duration) error {
	tk := fmt.Sprintf(tokenKey, platform, tools.MD5Encode(key))
	ot := 7 * 24 * time.Hour
	if len(timeout) > 0 {
		ot = timeout[0]
	}
	if err := utils.Cache.Put(tk, value, ot); err != nil {
		logs.Error("SetToken err:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}

// @title 获取token
// @param key string true token key
// @param platform string true 平台
func GetToken(key, platform string) string {
	tk := fmt.Sprintf(tokenKey, platform, tools.MD5Encode(key))
	data := utils.Cache.Get(tk)
	if data == nil {
		return ""
	}
	return fmt.Sprintf("%s", data)
}

// @title 删除token
// @param key string true token key
// @param platform string true 平台
func DeleteToken(key, platform string) error {
	tk := fmt.Sprintf(tokenKey, platform, tools.MD5Encode(key))
	return utils.Cache.Delete(tk)
}

// @title 刷新token
// @param key string true token key
// @param platform string true 平台
func RefreshToken(refresh_token, platform string, timeout ...time.Duration) (token, ref_token string, err error) {
	otk := GetToken(refresh_token, platform)
	if len(otk) == 0 {
		return "", "", errors.New("refresh_token not exists")
	}

	uid := GetToken(otk, platform)
	if len(uid) == 0 {
		return "", "", errors.New("old token not exists")
	}

	tk := tools.GUUID()
	ref := tools.GUUID()
	SetToken(tk, uid, platform, timeout...)
	SetToken(ref, tk, platform, 365*24*time.Hour)
	DeleteToken(otk, platform)
	DeleteToken(refresh_token, platform)

	return tk, ref, nil
}
